package org.september.pisces.excel.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.september.core.exception.BusinessException;
import org.september.pisces.excel.entity.ExcelTemplate;
import org.september.pisces.excel.service.PiscesExcelService;
import org.september.pisces.excel.vo.ExcelImage;
import org.september.pisces.filestore.entity.FileStoreItem;
import org.september.pisces.filestore.service.FileStoreManager;
import org.september.simpleweb.controller.BaseController;
import org.september.simpleweb.model.ResponseVo;
import org.september.smartdao.common.BaseService;
import org.september.smartdao.model.Page;
import org.september.smartdao.model.ParamMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.FileUtils;

import jakarta.servlet.http.HttpServletResponse;

/**
 * Excel模板管理
 */
@Controller
public class ExcelTmplController extends BaseController {

    @Autowired
    private BaseService baseService;

    @Autowired
    private PiscesExcelService piseceExcelService;

    @Autowired
    private FileStoreManager fileStoreManager;

    @RequestMapping(value = List_Page)
    public ModelAndView tmplList() throws Exception {
        ModelAndView mv = new ModelAndView();
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = List_Data)
    public ResponseVo<Page<ExcelTemplate>> listTmplData(Page<ExcelTemplate> page) throws Exception {
        ParamMap pm = new ParamMap();
        page = baseService.getCommonDao().findPageByParams(ExcelTemplate.class, page, "ExcelTemplate.listTmplData", pm);
        return ResponseVo.<Page<ExcelTemplate>>BUILDER().setData(page).setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @RequestMapping(value = Import_Action)
    public ResponseVo<String> doImportTmpl(MultipartFile file) throws Exception {
        if (file.getSize() <= 6604L) {
            return ResponseVo.<String>BUILDER().setDesc("上传的文件内容为空").setCode(ResponseVo.BUSINESS_CODE.FAILED);
        }
        List<ExcelTemplate> list = baseService.getCommonDao().listByParams(ExcelTemplate.class, "ExcelTemplate.listTmplData", new ParamMap());
        for (ExcelTemplate template : list) {
            if (template.getName().equals(file.getOriginalFilename())) {
                return ResponseVo.<String>BUILDER().setDesc("该文件已存在").setCode(ResponseVo.BUSINESS_CODE.FAILED);
            }
        }
        piseceExcelService.addExcelTmpl(file.getOriginalFilename(), file.getBytes());
        return ResponseVo.<String>BUILDER().setData("").setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @RequestMapping(value = Delete_Action)
    public ResponseVo<String> deleteTmpl(Long id) throws Exception {
        piseceExcelService.deleteTemplate(id);
        return ResponseVo.<String>BUILDER().setCode(ResponseVo.BUSINESS_CODE.SUCCESS);
    }

    @ResponseBody
    @RequestMapping(value = Download_Action)
    public void downloadTmpl(HttpServletResponse response, Long tplId) throws Exception {
        ExcelTemplate tpl = baseService.getCommonDao().get(ExcelTemplate.class, tplId);
        if (tpl == null) {
            throw new BusinessException("模板不存在");
        }
        FileStoreItem item = fileStoreManager.getFileItem(tpl.getFileUuid());
        InputStream ins = fileStoreManager.getInputStreamByUUID(item, false);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(tpl.getName(), "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        response.getOutputStream().write(IOUtils.toByteArray(ins));
        ins.close();
        response.getOutputStream().close();
    }

    @ResponseBody
    @RequestMapping(value = "/testExport")
    public void testExportExcel(HttpServletResponse response, Long tplId) throws Exception {
        ExcelTemplate tpl = baseService.getCommonDao().get(ExcelTemplate.class, tplId);
        if (tpl == null || tpl.getDeleteFlag() == 1) {
            throw new BusinessException("模板不存在");
        }
        List<Map<String, Object>> datas = new ArrayList<>();
        Map<String, Object> data1 = new HashMap<>();
        data1.put("name", "yexinzhou");
        data1.put("comp", getTestImageData());
        datas.add(data1);

        Map<String, Object> data2 = new HashMap<>();
        data2.put("name", "yexinzhou2");
        data2.put("comp", "dddz2");
        datas.add(data2);

        piseceExcelService.doExport(response, tpl.getName(), datas, "test.xlsx");
    }

    private ExcelImage getTestImageData() throws IOException {
        ExcelImage img = new ExcelImage();
        img.setDatas(FileUtils.readFileToByteArray(new File("D:\\work\\文档\\交通\\traffic\\项目信息\\安徽\\安庆\\两站一场总体方案.png")));
        return img;
    }

    private static final String Mapping_Prefix = "/pisces/excel";
    public static final String List_Page = Mapping_Prefix + "/tmplList";
    public static final String List_Data = Mapping_Prefix + "/listTmplData";
    public static final String Import_Action = Mapping_Prefix + "/doImportTmpl";
    public static final String Delete_Action = Mapping_Prefix + "/deleteTmpl";
    public static final String Download_Action = Mapping_Prefix + "/downloadTmpl";
}
